package cn.i7baozh.boot.learn.initializer.config;

import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangbaoqi532
 * @date 2025/2/19
 */
public class MyConfig {

    static volatile ConfigurableEnvironment environment;

    public static void init(ConfigurableEnvironment environment) {
        MyConfig.environment = environment;
    }

    public static String getProperty(String key) {
        return environment.getProperty(key);
    }

    public static void setProperty(String key, String value){
        MutablePropertySources propertySources = environment.getPropertySources();
        String propertySourceName = "xxx";
        PropertySource<?> xxx = propertySources.get(propertySourceName);
        if (xxx == null) {
            Map<String, Object> param = new HashMap<>();
            param.put(key, value);
            xxx = new OriginTrackedMapPropertySource(propertySourceName, param);
            propertySources.addFirst(xxx);
        } else {
            Map<String, Object> param = ((OriginTrackedMapPropertySource)xxx).getSource();
            param.put(key, value);
            propertySources.replace(propertySourceName, new OriginTrackedMapPropertySource(propertySourceName,
                    param));
        }
    }
}
